package com.bimbimbip.explorer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import com.bimbimbip.explorer.R;
import com.bimbimbip.manager.FileItemManager;
import com.bimbimbip.treeview.InMemoryTreeStateManager;
import com.bimbimbip.treeview.TreeBuilder;
import com.bimbimbip.treeview.TreeStateManager;
import com.bimbimbip.treeview.TreeViewList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ExplorerActivity extends Activity {

	
	// final GridView gridview;
	FileItemManager fileItemManager = new FileItemManager();
	final int properpties = 0x00000;
	GridView gridview;
	String lastPath = "", selectPath = "";
	int isCopy = 0;
	TextView textPath;
	private String currentPath = "/";
	LinearLayout linearLayout;
	ImageButton home_btn, sdcard_btn, search_btn, back_btn, view_btn;
	final int[] background = { R.drawable.a1253692265397665,
			R.drawable.a1254243247333102, R.drawable.a1254245467527970,
			R.drawable.a432_085042_1, R.drawable.a432_085350_1,
			R.drawable.a432_085502_1, R.drawable.a432_094539_1,
			R.drawable.a13288, R.drawable.a1_210947_1, R.drawable.a2666 };
	int i = 0;
	
	//Using listview to show treeview
	private final Set<Long> selected = new HashSet<Long>();
//    private static final String TAG = this.class.getSimpleName();
    private TreeViewList treeView;
    private int[] DEMO_NODES;
    
    private static final int LEVEL_NUMBER = 4;
    private TreeStateManager<Long> manager = null;
    private SimpleStandardAdapter simpleAdapter;
    @SuppressWarnings("unchecked")
	//end init treeview
    
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DEMO_NODES = new int[fileItemManager.DEMO_NODES_2.size()];
		fileItemManager.loadFileToSyncNode(DEMO_NODES);
		try {
			setContentView(R.layout.main);
			
			//build treeview.
	        if (savedInstanceState == null) {
	            manager = new InMemoryTreeStateManager<Long>();
	            final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
	            for (int i = 0; i < DEMO_NODES.length; i++) {
	                treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]);
	            }
//	            Log.d(TAG, manager.toString());
	        } else {
	            manager = (TreeStateManager<Long>) savedInstanceState
	                    .getSerializable("treeManager");
	        }
	        treeView = (TreeViewList) findViewById(R.id.mainTreeView);
	        simpleAdapter = new SimpleStandardAdapter(this, selected, manager,
	                LEVEL_NUMBER);
	        treeView.setAdapter(simpleAdapter);
	        treeView.setCollapsible(true);
	        registerForContextMenu(treeView);
	        //end build treeview.
	        
	        
			textPath = (TextView) findViewById(R.id.path);
			gridview = (GridView) findViewById(R.id.gridview);
//An nut home
			home_btn = (ImageButton) findViewById(R.id.home_btn);
			home_btn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {

					gridview.setAdapter(new ImageAdapter(ExplorerActivity.this,
							fileItemManager.getChild("/", textPath)));
					currentPath = "/";
				}
			});
//An nut back
			back_btn = (ImageButton) findViewById(R.id.back_btn);
			back_btn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					String parent = fileItemManager.getParent(currentPath);
					if (parent != null){
						gridview.setAdapter(new ImageAdapter(ExplorerActivity.this, fileItemManager.getChild(parent, textPath)));
					currentPath = parent;
					}
				}
			});
//An nut sdcard.
			sdcard_btn = (ImageButton) findViewById(R.id.sdcard_btn);
			sdcard_btn.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					gridview.setAdapter(new ImageAdapter(ExplorerActivity.this,fileItemManager.getChild("/sdcard", textPath)));
					currentPath = "//sdcard";
				}
			});
//An nut search
			search_btn = (ImageButton) findViewById(R.id.search_btn);
			search_btn.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					showSearchDialog();
				}
			});

			gridview.setAdapter(new ImageAdapter(this, fileItemManager.getChild("/", textPath)));
			currentPath = "/";
			registerForContextMenu(gridview);
//Nhan vao 1 item trong gridview thì hiện ra con của nó.
			gridview.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					String path = "";
					try {
						ViewFile item = (ViewFile) v.getTag();
						path = item.getFilePath();

						if (path == null) {
							return;
						}
						System.out.println(!new File(path).isFile());
						if (!new File(path).isFile()) {
							gridview.setAdapter(new ImageAdapter(
									ExplorerActivity.this, fileItemManager.getChild(path,textPath)));
							currentPath = path;
						} else {
							actionOpen(path);
						}

					} catch (Exception e) {
					}

				}
			});
		} catch (Exception e) {
			Toast.makeText(this, "LOOI tum lkoifisdjfsf", Toast.LENGTH_SHORT);
		}

		view_btn = (ImageButton) findViewById(R.id.view_btn);
		view_btn.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				onView();
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		selectPath = currentPath;
		switch (item.getItemId()) {
		case R.id.add:
			showCreateDialog();
			break;
		case R.id.refesh:
			onRefesh();
			break;
		case R.id.properties:
			onProperties();
			break;
		case R.id.edit:

			break;
		case R.id.setting:

			break;
		case R.id.about:
			showAboutDialog();
			Log.v("đâsdsadasd", currentPath);
			break;
		case R.id.cut:
			onCut();
			selectPath = "";
			break;
		case R.id.copy:
			onCopy();
			selectPath = "";
			break;
		case R.id.paste:
			onPaste();
			selectPath = "";
			break;
		case R.id.rename:

			showRenameDialog();

			break;
		case R.id.delete:
			onDelete();
			selectPath = "";
			break;
		case R.id.select_all:

			break;
		case R.id.rar:

			break;
		case R.id.tick:

			break;
		case R.id.find:

			break;
		case R.id.size:
			onChangeSize();
			break;

		default:
			break;
		}
		return true;
	}

	private void onChangeSize() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("CHANGE SIZE");
		builder.setItems(R.array.list_size,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						String[] items = getResources().getStringArray(
								R.array.list_size);
						Log.v("aaaaaaaaaaaa", items[which]);
						if (items[which].equalsIgnoreCase("Small")) {
							onSmall();
							Log.d("CHANGE SIZE", "onSmall()");
						} else if (items[which].equalsIgnoreCase("Medium")) {
							onMedium();
							Log.v("aaaaaaaaaaaa", items[which]);
						} else
							onLarge();

					}

					private void onLarge() {
						gridview = (GridView) findViewById(R.id.gridview);
						gridview.setColumnWidth(80);
						onRefesh();
					}

					private void onMedium() {
						gridview = (GridView) findViewById(R.id.gridview);
						gridview.setColumnWidth(60);
						onRefesh();
					}

					private void onSmall() {
						gridview = (GridView) findViewById(R.id.gridview);
						gridview.setColumnWidth(40);
						onRefesh();
					}
				});
		builder.create().show();

	}

	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		View v = info.targetView;
		ViewFile name = (ViewFile) v.getTag();
		selectPath = name.getFilePath();
		switch (item.getItemId()) {
		case R.id.cut:
			onCut();
			selectPath = "";
			break;
		case R.id.copy:
			onCopy();
			selectPath = "";
			break;
		case R.id.rename:

			showRenameDialog();

			break;
		case R.id.delete:
			onDelete();
			selectPath = "";
			break;
		case R.id.select_all:

			break;
		case R.id.rar:

			break;
		case R.id.tick:

			break;
		case R.id.find:

			break;
		case R.id.properties:

			onProperties();
			selectPath = "";
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	private void actionOpen(String path) {
		MimeTypeMap tMimeType = MimeTypeMap.getSingleton();
		String tMimeStr = tMimeType.getMimeTypeFromExtension(path.substring(
				path.length() - 3).toLowerCase());
		System.out.println(path.substring(path.length() - 3));
		Intent intent = new Intent();
		Uri data = Uri.parse("file://" + path);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(data, tMimeStr);
		try {
			startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(this,
					"Can not find any program associate with this file.",
					Toast.LENGTH_LONG).show();
		}
	}

	public void showCreateDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Enter new folder ");

		final EditText folder = new EditText(this);
		folder.setText("default");
		builder.setView(folder);

		builder.setPositiveButton("Create",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						final String folderName = folder.getText().toString()
								.trim();
						Log.v("bimbimbip", folderName);
						onCreateFolder(folderName);

					}

				});
		builder.setNegativeButton("Cancel !",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.create();
		builder.show();

	}

	public void onCreateFolder(String foldername) {

		Log.v("bimbimbip", foldername);

		if (foldername != null) {

			try {

				File file = new File(currentPath + "/" + foldername);

				if (file.exists()) {
					Toast.makeText(getApplicationContext(),
							"Folder already exit ", Toast.LENGTH_SHORT).show();
					Log.v("bimbimbip", currentPath);
				} else if (file.mkdir()) {
					Toast.makeText(getApplicationContext(),
							" Create folder is successly", Toast.LENGTH_SHORT)
							.show();
					Log.v("bimbimbip", currentPath);
				} else {
					Toast.makeText(getApplicationContext(),
							" Create folder is failed", Toast.LENGTH_SHORT)
							.show();
					Log.v("bimbimbip", currentPath);
				}
			} catch (Exception e) {

				Toast.makeText(getApplicationContext(), "huhuhhuhu ",
						Toast.LENGTH_SHORT);
			}

		}

		onRefesh();

	}

	public void onRename(String newname) {
		final File file = new File(selectPath);
		Log.v("selectPath", selectPath);
		if (newname != null) {
			try {
				File newFile = new File(file.getParent() + "/" + newname);

				if (newFile.exists()) {
					Toast.makeText(getApplicationContext(),
							"This name has been used by another file.",
							Toast.LENGTH_LONG).show();
				} else if (file.renameTo(newFile)) {
					Toast.makeText(getApplicationContext(),
							"Renaming is successly.", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getApplicationContext(),
							"Renaming is failed.", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						"Error " + e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}

	}

	public void showSearchDialog(){
		//String str;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Enter new search ");
		final EditText strSearch = new EditText(this);
		strSearch.setText("");
		builder.setView(strSearch);

		builder.setPositiveButton("Search",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String str = strSearch.getText().toString().trim();
						gridview.setAdapter(new ImageAdapter(ExplorerActivity.this, fileItemManager.search(currentPath, str))); //getChild(currentPath+"/dev")));//
					}
				});
		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) 
					{
					}
				});
		builder.create();
		builder.show();
		//onRefesh();
	}
	
	public void showRenameDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Enter new name ");

		final EditText folder = new EditText(this);
		folder.setText("default");
		builder.setView(folder);

		builder.setPositiveButton("Rename",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						final String newname = folder.getText().toString()
								.trim();
						Log.v("bimbimbip", newname);
						Log.v("selectPath", selectPath);
						onRename(newname);
						onRefesh();
					}

				});
		builder.setNegativeButton("Cancel !",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.create();
		builder.show();
		onRefesh();
	}

	private void onCut() {
		if (selectPath == null)
			return;
		if (new File(selectPath).isFile())
			Toast.makeText(
					this,
					"The file " + new File(selectPath).getName()
							+ " will move when you select command paste.",
					Toast.LENGTH_LONG).show();
		else
			Toast.makeText(
					this,
					"The folder " + new File(selectPath).getName()
							+ " will move when you select command paste.",
					Toast.LENGTH_LONG).show();
		lastPath = selectPath;
		isCopy = 1;
	}

	public void showAboutDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("ABOUT ME !!!!!!");

		final TextView tv = new TextView(this);
		tv.setText("Explorer bimbimbip version 1.0 CUI BAP ");
		builder.setView(tv);

		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {


			}

		});
		builder.setNegativeButton("Cancel !",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.create();
		builder.show();

	}

	public void onRefesh() {
		Log.v("currentPath On Refresh", currentPath);
		gridview.setAdapter(new ImageAdapter(this, fileItemManager.getChild(currentPath, textPath)));

	}

	public void onProperties() {
		String path = this.selectPath;
		if (path == null) {
			path = this.currentPath;
			Log.d("Properties ", "nuuuuuuuuuuuuuuuuuuuul");
		}
		File file = new File(path);
		if (file.isFile()) {
			Intent intent = new Intent(this, FileProperties.class);
			intent.putExtra("filename", selectPath);
			startActivityForResult(intent, properpties);
		} else {
			Intent intent = new Intent(this, FolderProperties.class);
			intent.putExtra("foldername", selectPath);
			startActivityForResult(intent, properpties);
		}
	}

	public void onChangeBackground() {
		if (i == background.length)
			i = 0;
		linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
		linearLayout.setBackgroundResource(background[i]);

		i++;
	}

	public void onView() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("VIEW");
		builder.setItems(R.array.list_dialog,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						String[] items = getResources().getStringArray(
								R.array.list_dialog);
						Log.v("aaaaaaaaaaaa", items[which]);
						if (items[which].equalsIgnoreCase("Change Background"))
							onChangeBackground();
						else if (items[which].equalsIgnoreCase("Show ListView")) {
							Toast.makeText(getApplicationContext(),
									items[which], Toast.LENGTH_SHORT);
							Log.v("aaaaaaaaaaaa", items[which]);
						} else
							Toast.makeText(getApplicationContext(),
									items[which], Toast.LENGTH_SHORT);

					}
				});
		builder.create().show();
	}

	public void onDelete() {
		final File file = new File(selectPath);
		if (file.isFile()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("DELETE FILE");
			TextView tv = new TextView(this);
			tv.setText("Are you sure delete file " + file.getName()
					+ " ???  You do not Crazy ??");
			builder.setView(tv);
			builder.setPositiveButton("Yes ",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							if (file.delete()) {
								Toast.makeText(getApplicationContext(),
										"File was deleted ...",
										Toast.LENGTH_SHORT).show();
								onRefesh();

							} else
								Toast.makeText(getApplicationContext(),
										"Delete is faild ...",
										Toast.LENGTH_SHORT).show();

						}
					});

			builder.setNegativeButton("Cancel ",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

						}
					});

			builder.create().show();

		} else {
			Log.i("Folder delete path", selectPath);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("DELETE FOLDER");
			TextView tv = new TextView(this);
			tv.setText("Are you sure delete folder " + file.getName()
					+ " ???  You do not Crazy ??");
			builder.setView(tv);
			builder.setPositiveButton("Yes",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

							// chua chay dc cai nay
							// Intent intent = new
							// Intent(ExplorerActivity.this,DeleteFolder.class);
							// intent.putExtra("foldername", selectPath);
							// Log.i("Folder delete path", selectPath);
							// startActivityForResult(intent, delete);

							Log.v("Folder delete", file.getName());
							deleteFolder(file);
							Log.d("TAGGGGGGGGGGGGGGGG", "deleteFolder()");
							onRefesh();

						}
					});

			builder.setNegativeButton("Cancel ",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {

						}
					});
			builder.create().show();

		}

	}

	public void deleteFolder(File folderdelete) {
		try {
			if (folderdelete.isDirectory()) {
				if (folderdelete.list().length == 0) {
					folderdelete.delete();
					Log.v("Directory is deleted",
							folderdelete.getAbsolutePath());
				} else {
					String children[] = folderdelete.list();
					for (String temp : children) {
						File fileDelete = new File(folderdelete, temp);
						deleteFolder(fileDelete);

					}
					if (folderdelete.list().length == 0) {
						folderdelete.delete();
						Log.v("Directory is deleted",
								folderdelete.getAbsolutePath());
					}
				}

			} else {
				folderdelete.delete();
				Log.v("Directory is deleted", folderdelete.getAbsolutePath());
			}
		} catch (Exception e) {
			Toast.makeText(this, "Error !!" + e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}

	}

	public void onCopy() {
		File file = new File(selectPath);
		if (selectPath == null)
			return;
		if (file.isFile()) {
			Toast.makeText(ExplorerActivity.this, "This file is already copy ",
					Toast.LENGTH_LONG).show();
		} else
			Toast.makeText(ExplorerActivity.this,
					"This folder is already copy ", Toast.LENGTH_LONG).show();
		lastPath = selectPath;
		isCopy = 2;

	}

	public void onPaste() {
		if (lastPath == "") {
			Toast.makeText(
					this,
					" You must select file or folder and choose copy or cut before paste ! ",
					Toast.LENGTH_LONG).show();
			return;
		}
		File src = new File(lastPath);
		if (src.getParent() == currentPath) {
			Toast.makeText(
					this,
					"Error duplication in a directory....you must select a diffrent directory !",
					Toast.LENGTH_LONG);
			return;
		}

		if (isCopy == 2) {
			if (true) {
				/*
				 * File source = new File(lastPath); File target = new
				 * File(currentPath + "/" + src.getName());
				 * onCopyToPaste2(source,target); Log.v("bimbimbip",
				 * "onCopyToPaste");
				 */

				Intent intent = new Intent(ExplorerActivity.this,
						FolderCopy.class);
				intent.putExtra("foldersource", lastPath);
				intent.putExtra("foldertarget",
						currentPath + "/" + src.getName());
				startActivityForResult(intent, 0x000111);
				onRefesh();

			}

		} else if (isCopy == 1) {
			onCutToPaste();
		} else
			Toast.makeText(
					this,
					" You must select file or folder and choose copy or cut before paste ! ",
					Toast.LENGTH_SHORT).show();

		isCopy = 0;

	}

	private void onCutToPaste() {
		File src = new File(lastPath);
		File des = new File(currentPath + "/" + src.getName());
		try {
			if (src.renameTo(des)) {
				Toast.makeText(this, " Cut and paste is success !!!!  ",
						Toast.LENGTH_LONG).show();
			} else
				Toast.makeText(this, " Cut and paste was failed !!!!  ",
						Toast.LENGTH_LONG).show();

		} catch (Exception e) {
		}
		onRefesh();

	}

	public void onCopyToPaste2(File source, File target) {

		try {

			if (source.isDirectory()) {
				if (!target.exists()) {
					target.mkdir();
				}

				String[] children = source.list();
				for (int i = 0; i < children.length; i++) {
					onCopyToPaste2(new File(source, children[i]), new File(
							target, children[i]));
				}
			} else {
				InputStream in = new FileInputStream(source);
				OutputStream out = new FileOutputStream(target);
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();

			}

		} catch (Exception e) {
			Toast.makeText(this, "Error !! " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

		onRefesh();
	}

}
